package com.example.worddemo;

import com.spire.doc.*;
import com.spire.doc.documents.Paragraph;
import com.spire.doc.fields.DocPicture;
import com.spire.doc.fields.TextRange;
import com.spire.xls.*;

import java.awt.*;

/**
 * fixme JDK17异常
 * 装doc到excel
 */
public class ConvertWordToExcel {

    public static void main(String[] args) {

        //创建一个 Document 对象
        Document doc = new Document();

        //加载 Word 文件
        doc.loadFromFile("创建表格.docx");

        //创建一个 Workbook 对象
        Workbook wb = new Workbook();

        //删除默认工作表
        wb.getWorksheets().clear();

        //创建一个名为“WordToExcel”的工作表
        Worksheet worksheet = wb.createEmptySheet("WordToExcel");
        int row = 1;
        int column = 1;

        //循环遍历 Word 文档中的各个节
        for (int i = 0; i < doc.getSections().getCount(); i++) {
            //获取特定节
            Section section = doc.getSections().get(i);

            //遍历某个节下的所有文档对象
            for (int j = 0; j < section.getBody().getChildObjects().getCount(); j++) {
                //获取特定的文档对象
                DocumentObject documentObject = section.getBody().getChildObjects().get(j);

                //判断对象是否为段落
                if (documentObject instanceof Paragraph) {
                    CellRange cell = worksheet.getCellRange(row, column);
                    Paragraph paragraph = (Paragraph) documentObject;
                    //将段落从 Word 复制到特定单元格
                    copyTextAndStyle(cell, paragraph);
                    row++;
                }

                //判断对象是否为表格
                if (documentObject instanceof Table) {
                    Table table = (Table) documentObject;
                    //将表格数据从 Word 导出到 Excel
                    int currentRow = exportTableInExcel(worksheet, row, table);
                    row = currentRow;
                }
            }
        }

        //在单元格中换行文本
        worksheet.getAllocatedRange().isWrapText(true);

        //自动调整行高和列宽
        worksheet.getAllocatedRange().autoFitRows();
        worksheet.getAllocatedRange().autoFitColumns();

        //将工作簿保存到 Excel 文件
        wb.saveToFile("output.xlsx", ExcelVersion.Version2013);
    }

    //将数据从 Word 表格导出到 Excel 单元格
    private static int exportTableInExcel(Worksheet worksheet, int row, Table table) {
        CellRange cell;
        int column;
        for (int i = 0; i < table.getRows().getCount(); i++) {
            column = 1;
            TableRow tbRow = table.getRows().get(i);
            for (int j = 0; j < tbRow.getCells().getCount(); j++) {
                TableCell tbCell = tbRow.getCells().get(j);
                cell = worksheet.getCellRange(row, column);
                cell.borderAround(LineStyleType.Thin, Color.BLACK);
                copyContentInTable(tbCell, cell);
                column++;
            }
            row++;
        }
        return row;
    }

    //将内容从 Word 表格单元格复制到 Excel 单元格
    private static void copyContentInTable(TableCell tbCell, CellRange cell) {
        Paragraph newPara = new Paragraph(tbCell.getDocument());
        for (int i = 0; i < tbCell.getChildObjects().getCount(); i++) {
            DocumentObject documentObject = tbCell.getChildObjects().get(i);
            if (documentObject instanceof Paragraph) {
                Paragraph paragraph = (Paragraph) documentObject;
                for (int j = 0; j < paragraph.getChildObjects().getCount(); j++) {
                    DocumentObject cObj = paragraph.getChildObjects().get(j);
                    newPara.getChildObjects().add(cObj.deepClone());
                }
                if (i < tbCell.getChildObjects().getCount() - 1) {
                    newPara.appendText("\n");
                }
            }
        }
        copyTextAndStyle(cell, newPara);
    }

    //将段落的文本和样式复制到单元格
    private static void copyTextAndStyle(CellRange cell, Paragraph paragraph) {

        RichText richText = cell.getRichText();
        richText.setText(paragraph.getText());
        int startIndex = 0;
        for (int i = 0; i < paragraph.getChildObjects().getCount(); i++) {
            DocumentObject documentObject = paragraph.getChildObjects().get(i);
            if (documentObject instanceof TextRange) {
                TextRange textRange = (TextRange) documentObject;
                String fontName = textRange.getCharacterFormat().getFontName();
                boolean isBold = textRange.getCharacterFormat().getBold();
                Color textColor = textRange.getCharacterFormat().getTextColor();
                float fontSize = textRange.getCharacterFormat().getFontSize();
                String textRangeText = textRange.getText();
                int strLength = textRangeText.length();
                ExcelFont font = new ExcelFont(cell.getWorksheet().getWorkbook().createFont());
                font.setColor(textColor);
                font.isBold(isBold);
                font.setSize(fontSize);
                font.setFontName(fontName);
                int endIndex = startIndex + strLength;
                richText.setFont(startIndex, endIndex, font);
                startIndex += strLength;
            }
            if (documentObject instanceof DocPicture) {
                DocPicture picture = (DocPicture) documentObject;
                cell.getWorksheet().getPictures().add(cell.getRow(), cell.getColumn(), picture.getImage());
                cell.getWorksheet().setRowHeightInPixels(cell.getRow(), 1, picture.getImage().getHeight());
            }
        }
        switch (paragraph.getFormat().getHorizontalAlignment()) {
            case Left:
                cell.setHorizontalAlignment(HorizontalAlignType.Left);
                break;
            case Center:
                cell.setHorizontalAlignment(HorizontalAlignType.Center);
                break;
            case Right:
                cell.setHorizontalAlignment(HorizontalAlignType.Right);
                break;
        }
    }
}